package com.cloudkinto.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.cloudkinto.common.constant.GlobalConstants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Qoo10Utils {
    public static final String QOO_BASE_URL = "http://api.qoo10.jp/GMKT.INC.Front.QAPIService/ebayjapan.qapi";


    public static String okHttpRequestPost(String requestUrl, String accessToken, Map<String, Object> paramMap) {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
        headerMap.put("QAPIVersion", "1.0");
        headerMap.put("GiosisCertificationKey", accessToken);

        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(false);
        Request.Builder request = new Request.Builder();
        for (String key : headerMap.keySet()) {
            request.addHeader(key, headerMap.get(key));
        }

        Request build = request.url(requestUrl)
                .post(RequestBody.create(MediaType.get("application/json"), JSONObject.toJSONString(paramMap)))
                .build();
        System.out.println(paramMap);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(build).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }



    public static String getQoo10Token(String sellerId, String appKey, String appSecret) {
        StringBuilder url = new StringBuilder(QOO_BASE_URL);

        url.append("?v=1.0&").append("&returnType=json&method=CertificationAPI.CreateCertificationKey");
        if (StringUtils.isNotBlank(appKey)) {
            url.append("&key=").append(appKey);
        }
        if (StringUtils.isNotBlank(sellerId)) {
            url.append("&user_id=").append(sellerId);
        }
        if (StringUtils.isNotBlank(appSecret)) {
            try {
                appSecret = URLEncoder.encode(appSecret, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return null;
            }
            url.append("&pwd=").append(appSecret);
        }
        String body = "";
        JSONObject keyObject = null;
        try {
            //ResultCode 成功的时候 是0
            body = okHttpRequestGet(url.toString());
            //{
            //  "ResultObject": null,
            //  "ResultCode": -1,
            //  "ResultMsg": "システムエラー"
            //}
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(body)) {
            return null;
        }
        keyObject = JSONObject.parseObject(body);
        if (keyObject == null) {
            return null;
//            throw new BizException(SysConstant.Error_SecretKey_Expired_Sync);
        }
        String key = keyObject.getString("ResultObject");
        return key;
    }


    private static Map<String, String> handlerKeyParam(String sellerId, String appKey, String appSecret) {
        Map<String, String> map = new HashMap<>();
        map.put("id", sellerId);
        map.put("key", appKey);
        map.put("pwd", appSecret);
        return map;
    }


    public static String okHttpRequestGet(String requestUrl) {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(false);
        String url = requestUrl;
        Request request = new Request.Builder()
//                .addHeader("Content-type", "application/json")
//                .addHeader("Host", "api.rms.rakuten.co.jp")
//                .addHeader("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
//                .addHeader("User-Agent", Version.userAgent())
//                .addHeader("companyId", "1")
//                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNTY5ODk4ODQxfQ.nQdV49X8jKLW3qHQYsXBC8qVrSyfYLBPiF1qHGVQsxk")
                .url(requestUrl)
                .get()
                .build();
//        System.out.println(url);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(request).execute();
            body = response.body().string();
//            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }


    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, getX509TrustManager());

            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 功能描述 添加sslSocketFactory 证书验证
     *
     * @author zhujiale
     * @date 2022 03 02
     */
    public static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }

}
